// 购物车类
class ShoppingCart {
  constructor() {
    this.products = []; // 购物车中的商品列表
  }

  // 新增商品
  addItem(item) {
    const index = this.products.findIndex((target) => target.id === item.id);
    if (index == -1) {
      this.products.push({ ...item, quantity: 1 });
    } else {
      this.products[index].quantity += 1;
    }
  }

  // 删除指定商品
  removeItem(itemToRemove) {
    this.products = this.products.filter((item) => item.id !== itemToRemove);
  }

  // 获取购物车商品总价
  getTotal() {
    let total = 0;
    this.products.forEach((item) => {
      if (item.price) {
        total += (item.price * 1000 * item.quantity) / 1000;
      }
    });
    return total.toFixed(2);
  }

  // 获取购物车商品总数量
  getTotalQuantity() {
    let total = 0;
    this.products.forEach((item) => {
      if (item.quantity) {
        total += item.quantity;
      }
    });
    return total; // 获取购物车商品总价
  }
}

// 整个页面类
class Page {
  #timer = null;

  constructor() {
    // 页面dom元素
    this.doms = {
      productListBox: document.querySelector("#product-list"), //商品列表节点
      shoppingCart: document.querySelector(".shopping-cart"), //购物车按钮节点
      shoppingCartQuantity: document.querySelector("#shopping-cart-quantity"), //购物车数量节点
      shoppingCartPopup: document.querySelector("#shopping-cart-popup"), //购物车弹框节点
      cartBox: document.querySelector("#cart-box"), //购物车商品列表节点
    };
    // 购物车实例
    this.cart = new ShoppingCart();
    // 创建页面
    this.createHTML();
    // 监听事件
    this.listenEvent();
  }

  // 监听事件
  listenEvent() {
    // 购物车动画
    this.doms.shoppingCart.addEventListener("animationend", function () {
      this.classList.remove("animate");
    });

    // 监听鼠标移入购物车按钮
    this.doms.shoppingCart.addEventListener("mouseover", () => {
      if (this.#timer) {
        clearTimeout(this.#timer);
      }
      this.showCart();
    });

    // 监听鼠标移出购物车按钮
    this.doms.shoppingCart.addEventListener("mouseleave", () => {
      this.#timer = setTimeout(() => {
        this.hideCart();
      }, 200);
    });
    // 监听鼠标移入购物车弹框
    this.doms.shoppingCartPopup.addEventListener("mouseenter", () => {
      if (this.#timer) {
        clearTimeout(this.#timer);
      }
      this.showCart();
    });

    // 监听鼠标移出购物车弹框
    this.doms.shoppingCartPopup.addEventListener("mouseleave", () => {
      this.timer = setTimeout(() => {
        this.hideCart();
      }, 200);
    });
  }

  // 创建页面
  createHTML() {
    fetch("products.json")
      .then((response) => response.json())
      .then((data) => {
        const products = data;
        // 使用documentFragment批量更新DOM,减少dom操作
        const frag = document.createDocumentFragment();
        // 遍历商品数据,渲染到dom树上
        products.forEach((product) => {
          const productJson = JSON.stringify(product).replace(/"/g, "&quot;");
          const productItemInnerHtml = `
                        <img class="product-image" src="${product.image}" alt="${product.name}" />
                        <div class="product-info-box">
                            <div class="product-name" title="${product.name}">${product.name}</div>
                            <div class="product-price">¥${product.price}</div>
                            <button class="add-cart-btn" id="add-btn-${product.id}" type="button" onclick="page.addToCart(${productJson})">加入购物车</button>
                        </div>`;
          const productItem = this.addElement("div", "product-item", productItemInnerHtml);
          frag.appendChild(productItem);
        });

        this.doms.productListBox.innerHTML = "";
        this.doms.productListBox.appendChild(frag);
      })
      .catch((error) => console.error(error));
  }

  // 更新购物车商品数量
  updateProductQuantity() {
    let totalQuantity = this.cart.getTotalQuantity();
    if (totalQuantity <= 0) {
      totalQuantity = "";
      this.doms.shoppingCartPopup.style.display = "none";
      this.doms.shoppingCartPopup.offsetWidth;
      console.log(this.doms.shoppingCartPopup.style.display, 6666);
    }
    this.doms.shoppingCartQuantity.textContent = totalQuantity;
  }

  // 加入商品到购物车
  addToCart(item) {
    this.doms.shoppingCartPopup.style.display = "none"; //关闭购物车弹框
    this.cart.addItem(item); //加入购物车
    this.updateProductQuantity();
    // 加入购物车动画
    this.doms.shoppingCart.classList.add("animate");

    // 获取加入购物车按钮位置
    const btn = document.getElementById(`add-btn-${item.id}`);
    const btnRect = btn.getBoundingClientRect();
    //设置动效球起始位置
    const startPosition = {
      x: btnRect.left + btnRect.width / 2 - 10,
      y: btnRect.top,
    };

    // 创建动效球元素
    const plusPoint = this.addElement("div", "plus");
    document.body.appendChild(plusPoint);
    plusPoint.style.transform = `translate(${startPosition.x}px,${startPosition.y}px)`;
    // 强行渲染,才能执行css transition
    plusPoint.clientWidth;

    // 获取购物车坐标
    const cartRect = this.doms.shoppingCartQuantity.getBoundingClientRect();
    // 动效球最终目的地坐标
    const targtPosition = {
      x: cartRect.left - 10,
      y: cartRect.top,
    };

    plusPoint.style.transform = `translate(${targtPosition.x}px,${targtPosition.y}px)`;

    // 动效结束后删除元素
    plusPoint.addEventListener("transitionend", () => {
      plusPoint.remove();
    });
  }

  // 删除购物车指定商品
  delFromCart(item) {
    if (window.confirm("确认删除吗?")) {
      this.cart.removeItem(item.id);
      this.createCartHtml();
      this.updateProductQuantity();
    } else {
      console.log("取消。");
    }
  }

  // 展示购物车弹框
  showCart() {
    this.doms.shoppingCartPopup.style.display === "block";
    this.createCartHtml();
  }

  // 隐藏购物车弹框
  hideCart() {
    this.doms.shoppingCartPopup.style.display = "none";
  }

  // 绘制购物车页面
  createCartHtml() {
    if (this.cart.products.length > 0) {
      // 使用documentFragment批量更新DOM,减少dom操作
      const frag = document.createDocumentFragment();
      // 遍历商品数据,渲染到dom树上
      this.cart.products.forEach((product) => {
        const productJson = JSON.stringify(product).replace(/"/g, "&quot;");
        const productItemInnerHtml = `
                    <div class="product-name" title="${product.name}">${product.name}</div>
                    <div class="product-price">¥${product.price}</div>
                    <div class="product-quantity">*${product.quantity}</div>
                    <button class="del-btn" type="button" onclick="page.delFromCart(${productJson})">删除</button>
                  `;
        const productItem = this.addElement("div", "product-item", productItemInnerHtml);
        frag.appendChild(productItem);
      });
      // 删除旧节点
      this.doms.cartBox.innerHTML = "";
      // 生成新节点
      this.doms.cartBox.appendChild(frag);
    } else {
      this.doms.cartBox.innerHTML = `<div class="no-data">赞无商品</div>`;
    }

    this.doms.shoppingCartPopup.style.display = "block";
  }

  // 去购买
  toPay() {
    if (this.cart.products.length === 0) {
      alert("请先添加商品");
      return;
    }
    // 确认弹框
    if (window.confirm("确认购买吗?")) {
      alert(`商品总价为:¥${this.cart.getTotal()}`);
      this.doms.shoppingCartPopup.style.display = "none"; //关闭购物车弹框
    } else {
      console.log("取消。");
    }
  }

  // 创建dom元素
  addElement(tagName = "div", className = "", innerHTML = "") {
    // 创建新元素
    const newElement = document.createElement(tagName);
    // 设置元素类名
    newElement.className = className;
    // 设置元素内部HTML
    newElement.innerHTML = innerHTML;
    return newElement;
  }
}

// 创建页面实例
const page = new Page();
